package jude.java.money.batch.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import jude.java.money.batch.Definition;
import jude.java.money.batch.Parameter;
import jude.java.money.batch.task.expand.UpdateDatabaseTask;

import org.apache.commons.lang.StringUtils;


/**
 * 执行Wordpress SQL
 * */
public class BatchWordpressSql extends BatchFile implements UpdateDatabaseTask {
	
	public BatchWordpressSql(String sqlFile) {
		super(getParameter(sqlFile));
	}
	
	public BatchWordpressSql(String... sqls) {
		super(getParameter(sqls));
	}
	
	@Deprecated
	public BatchWordpressSql(String sqlTpl, int count) {
		super(getParameter(sqlTpl, count));
	}
	
	@Override
	protected void execute(String site, String url, int group, int index)
			throws IOException {
//		if (group != 2)
//			return;
//		if (index > 0)
//			return;
		super.execute(site, url, group, index);
	}
	
//	@Override
//	protected boolean skipSameDB() {
//		return true;
//	}
	
	private static Parameter<String[]> getParameter(String tpl, int count) {
		if (tpl.indexOf(Definition.DB_PREFIX) != -1 && count > 0) {
			String[] sqls = new String[count + 1];
			for(int i = 0; i <= count; i++) {
				sqls[i] = StringUtils.replace(tpl, Definition.DB_PREFIX, getPrefix(i));
			}
			return getParameter(sqls);
		}
		return getParameter(new String[] {tpl});
	}
	
	private static String getPrefix(int index) {
		if (index == 0)
			return "wp_";
		return "wp" + index + "_";
	}
	
	private static Parameter<String[]> getParameter(String[] sqls) {
		List<String> ps = new ArrayList<String>();
		ps.add("wp_sql.php");
		StringBuffer sb = new StringBuffer();
		for (String sql : sqls) {
			if (sb.length() > 0)
				sb.append("\r\n");
			sb.append(sql);
		}
//		if (sqls.length > 1) {
//			ps.add("sql_count");
//			ps.add(String.valueOf(sqls.length));
//		}
		ps.add("sql");
		ps.add(sb.toString());
		return Parameter.wordpress(ps.toArray(new String[ps.size()]));
	}
	
	private static Parameter<String[]> getParameter(String file) {
		try {
			InputStream in = BatchWordpressSql.class.getResourceAsStream(BASE_PATH + file);
			List<String> sqls = getSqls(in);
			return getParameter(sqls.toArray(new String[sqls.size()]));
		} catch (IOException e) {
		}
		return null;
	}
	
	private static List<String> getSqls(InputStream is) throws IOException {
		Reader reader = new InputStreamReader(is, "UTF-8");
		BufferedReader in = new BufferedReader(reader);
		ArrayList<String> sqls = new ArrayList<String>();
		String line;
		while ((line = in.readLine()) != null){
			line = line.trim();
			if (StringUtils.isNotEmpty(line))
				sqls.add(line);
		}
		return sqls;
	}
	
	@Override
	protected String getLabel() {
		return "WSQL";
	}
	
}
